package com.mk.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mk.constant.RedisCacheConstant;
import com.mk.context.BaseContext;
import com.mk.dto.CommentDTO;
import com.mk.entity.Article;
import com.mk.entity.Comment;
import com.mk.enumeration.LikedStatusEnum;
import com.mk.result.Result;
import com.mk.service.ICommentService;
import com.mk.utils.RedisUtil;
import com.mk.vo.CommentVO;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Options;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社区评论相关业务
 */
@RestController
@RequestMapping("/user/comment")
@RequiredArgsConstructor
public class CommentController {

    private final ICommentService commentService;
    private final RedisUtil redisUtil;
    private final HashMap<String, String> hm = new HashMap<>();

    /**
     * 给社区文章评论
     * @param commentDTO
     * @return
     */
    @CrossOrigin
    @PostMapping("/publish/article")
    @Options(keyProperty = "id", useGeneratedKeys = true)
    public Result publishToArticle(@RequestBody CommentDTO commentDTO) {
        Comment comment = BeanUtil.copyProperties(commentDTO, Comment.class);
        comment.setUserId(BaseContext.getCurrentId());
        comment.setCreateTime(LocalDateTime.now());
        commentService.save(comment);

        if (!hm.isEmpty()) hm.clear();
        putComment(Comment.USER_ID, comment.getUserId().toString());
        putComment(Comment.CONTENT, comment.getContent());
        putComment(Comment.IMAGE, comment.getImage());
        putComment(Comment.BE_LIKED, comment.getBeLiked().toString());
        putComment(Comment.CREATE_TIME, comment.getCreateTime().toString());

        redisUtil.add(RedisCacheConstant.COMMENT_KEY + comment.getId() + ":" + Comment.REDIS_ARTICLE_KEY + comment.getArticleId(), hm);
        return Result.success();
    }

    /**
     * 给社区别人发的评论评论
     * @param commentDTO
     * @return
     */
    @CrossOrigin
    @PostMapping("/publish/comment")
    public Result publishToComment(@RequestBody CommentDTO commentDTO) {
        Comment comment = BeanUtil.copyProperties(commentDTO, Comment.class);
        comment.setUserId(BaseContext.getCurrentId());
        comment.setCreateTime(LocalDateTime.now());
        commentService.save(comment);

        if (!hm.isEmpty()) hm.clear();
        putComment(Comment.USER_ID, comment.getUserId().toString());
        putComment(Comment.CONTENT, comment.getContent());
        putComment(Comment.IMAGE, comment.getImage());
        putComment(Comment.BE_LIKED, comment.getBeLiked().toString());
        putComment(Comment.CREATE_TIME, comment.getCreateTime().toString());

        redisUtil.add(RedisCacheConstant.COMMENT_KEY + comment.getId() + ":" + Comment.REDIS_DISCUSS_KEY + comment.getDiscussId(), hm);
        return Result.success();
    }

    /**
     * 根据文章id查询它所有的评论
     * @param articleId
     * @return
     */
    @CrossOrigin
    @GetMapping("/{articleId}")
    public Result<List<CommentVO>> getCommentByArticle(@PathVariable Long articleId) {
        List<Comment> commentList = commentService.list(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getArticleId, articleId));
        return Result.success(BeanUtil.copyToList(commentList, CommentVO.class));
    }

    /**
     * 根据评论id查询评论它的所有评论
     * @param discussId
     * @return
     */
    @CrossOrigin
    @GetMapping("/{discussId}")
    public Result<List<CommentVO>> getCommentByDiscuss(@PathVariable Long discussId) {
        List<Comment> commentList = commentService.list(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getDiscussId, discussId));
        return Result.success(BeanUtil.copyToList(commentList, CommentVO.class));
    }

    /**
     * 删除一条文章的评论
     * @param id
     * @return
     */
    @CrossOrigin
    @DeleteMapping("/delete/article")
    public Result deleteCommentOnArticle(Long id, Long articleId) {
        Map<Object, Object> map = redisUtil.getHashEntries(RedisCacheConstant.COMMENT_KEY + id + ":" + Comment.REDIS_ARTICLE_KEY + articleId);
        if (!map.isEmpty()) redisUtil.delete(RedisCacheConstant.COMMENT_KEY + id + ":" + Comment.REDIS_ARTICLE_KEY + articleId);
        commentService.removeById(id);
        return Result.success();
    }

    /**
     * 删除一条评论的评论
     * @param id
     * @return
     */
    @CrossOrigin
    @DeleteMapping("/delete/discuss")
    public Result deleteCommentOnDiscuss(Long id, Long discussId) {
        Map<Object, Object> map = redisUtil.getHashEntries(RedisCacheConstant.COMMENT_KEY + id + ":" + Comment.REDIS_DISCUSS_KEY + discussId);
        if (!map.isEmpty()) redisUtil.delete(RedisCacheConstant.COMMENT_KEY + id + ":" + Comment.REDIS_DISCUSS_KEY + discussId);
        commentService.removeById(id);
        return Result.success();
    }

    /**
     * 点赞评论
     * @param id
     * @return
     */
    @CrossOrigin
    @PostMapping("/like/{id}")
    public Result likeComment(@PathVariable Long id) {
        StringBuilder sb = new StringBuilder();
        String key = sb.append(id).append("::").append(BaseContext.getCurrentId()).toString();
        if (!hm.isEmpty()) hm.clear();
        putComment(key, LikedStatusEnum.LIKE.getCode().toString());
        redisUtil.add(RedisCacheConstant.LIKE_COMMENT_KEY, hm);

        return Result.success();
    }

    /**
     * 取消点赞评论
     * @param id
     * @return
     */
    @CrossOrigin
    @DeleteMapping("/unLike/{id}")
    public Result unLikeComment(@PathVariable Long id) {
        StringBuilder sb = new StringBuilder();
        String key = sb.append(id).append("::").append(BaseContext.getCurrentId()).toString();
        if (redisUtil.getHashEntries(RedisCacheConstant.LIKE_COMMENT_KEY).containsKey(key)) {
            redisUtil.delete(RedisCacheConstant.LIKE_COMMENT_KEY, key);
            return Result.success();
        } else {
            return Result.error("你并未点赞该评论");
        }
    }

    /**
     * 获取评论点赞数
     * @param id
     * @return
     */
    @CrossOrigin
    @GetMapping("/getLikeCount/{id}")
    public Result<Long> getLikeCount(@PathVariable Long id) {
        Comment comment = commentService.getById(id);
        return Result.success(comment.getBeLiked());
    }

    private void putComment(String key, String value) {
        hm.put(key, value);
    }
}
